package router

import (
	"net/http"
	"strings"
)

type RouteHandler struct{}

type RouteItem struct {
	Method string
	Path   string
}

// ServeHTTP 重写ServeHTTP
func (h *RouteHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	// 解决跨域
	w.Header().Set("Access-Control-Allow-Origin", "*")
	w.Header().Add("Access-Control-Allow-Headers", "Content-Type,AccessToken,X-CSRF-Token,token")
	w.Header().Add("Access-Control-Allow-Credentials", "true")
	w.Header().Add("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE")
	w.Header().Set("content-type", "application/json;charset=UTF-8")
	// 获取路由列表
	routes := Routes()
	// 获取当前路由作为Key
	url := r.URL.String()
	urlArr := strings.Split(url, "?")
	url = url[:len(urlArr[0])]
	routerItem := RouteItem{Method: r.Method, Path: url}
	if r.Method == "OPTIONS" {
		w.WriteHeader(http.StatusNoContent)
		return
	}
	// 查询路由是否存在
	if handler, ok := routes[routerItem]; ok {
		handler(w, r)
		return
	}
	w.WriteHeader(http.StatusNotFound)
}
